import { defineStore } from "pinia"
import { onMounted, ref } from "vue"
import { MessagePlugin } from "tdesign-vue-next"
import { throttle } from "@/utils/throttle"

export const useThemeModeStore = defineStore("themeMode", ()=>{
  const isLight = ref()
  // Initialize theme style following system
  const initThemeMode = () => {
    const themeMode = localStorage.getItem("themeMode")
    if (themeMode) {
      document.documentElement.setAttribute("theme-mode", themeMode)
      isLight.value = themeMode !== "light"
    } else {
      // Obtain system theme
      const darkModeMediaQuery = window.matchMedia("(prefers-color-scheme: dark)")
      const themeMode = darkModeMediaQuery.matches ? "dark" : "light"
      localStorage.setItem("themeMode", themeMode)
      document.documentElement.setAttribute("theme-mode", themeMode)
      isLight.value = themeMode === "dark"
    }
  }
  onMounted(() => {
    initThemeMode()
  })
  // Change theme style
  const changeThemeMode = () => {
    isLight.value = !isLight.value
    const themeMode = isLight.value ? "dark" : "light"
    document.documentElement.setAttribute("theme-mode", themeMode)
    localStorage.setItem("themeMode", themeMode)
    MessagePlugin("info", themeMode == "light" ? "已经入浅色模式！" : "已进入深色模式！", 1500).then()
  }
  // Throttling treatment
  const change = throttle(changeThemeMode, 1500)
  return {
    isLight,
    change,
  }
})
